import React, {PureComponent, Fragment} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Link, routerRedux} from 'dva/router';
import {status, statusMap} from './orderStatus';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Table,
  Tooltip,
  Tag,
} from 'antd';
const {RangePicker} = DatePicker;
import StandardTable from 'components/UnPayOrderTable';
import styles from './OrderList.less';
import G from '../../utils/g';

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const columns = [
  {
    title: '订单号',
    dataIndex: 'orderId',
    key: 'orderId',
    width: 80,
    render(text, record){
      let result = text.toString();
      return <Link to={`order-detail?id=${record.orderId}`}>{result.substr(result.length - 4)}</Link>; //取后四位显示
    }
  },
  {
    title: '商品',
    width: 300,
    dataIndex: 'name',
    render(text, record){
      let result = '';
      const sku = JSON.parse(record.sku);
      for (let key in sku) {
        result = record.sku[key];
      }
      return (<div>
          <img className={styles.goodsPic} src={`${record.img}?imageView2/1/w/50`} width={50} />
          <p className={styles.goodsName}>
            {record.name} × {record.count}<br/>
            <span className={styles.goodsColor}>{
              result
            }</span>
          </p>
        </div>)
    }
  },
  {
    title: '买家信息',
    align: 'right',
    render: (val, record)=> {
      return (<div>
        {record.nickname}<br/>
        {record.addressee} / {record.phone}
      </div>);
    }
  },
  {
    title: '下单时间',
    dataIndex: 'createTime',
    sorter: true,
    render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
  },
  {
    title: '商家',
    dataIndex: 'goods_nickname',
    key: 'goods_nickname'
  },
  {
    title: '单价',
    dataIndex: 'unit_price',
  },
  {
    title: '支付金额',
    dataIndex: 'price',
    key: 'price'
  },
  {
    title: '结算价',
    dataIndex: 'settlement_price',
    key: 'settlement_price'
  },
  {
    title: '结算小计',
    dataIndex: 'settlement_total',
    key: 'settlement_total',
    total:true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    render: (text)=>{
      return text === 0 ? <Tag color="volcano">异常订单</Tag>: ''
    }
  },
];

@connect(({businessPay, loading}) => ({
  businessPay,
  loading: loading.models.businessPay,
}))
@Form.create()
export default class TableList extends PureComponent {
  state = {
    modalVisible: true,
    expandForm: false,
    selectedRowKeys: [],
    selectedOrder: [], //记录选中正常订单，用于提交
    selectedRefund: [],  // 记录选中异常订单，用于提交
    totalPrice: 0,
    formValues: {},
    allDataList: [],  //保存全部订单列表记录， 用于计算总金额
  };

  componentDidMount() {
    const {dispatch,
      id
    } = this.props;

    let orderList = [];
    dispatch({
      type: 'businessPay/fetchBusinessOrderList',
      payload: {
        business_id : id
      }
    }).then((order)=>{
      orderList = order;
      return dispatch({ //获取异常订单
        type: 'businessPay/fetchBusinessRefundOrder',
        payload: {
          business_id : id
        }
      });
    }).then(res=>{
      // let totalPrice = 0;
      const allList = orderList.concat(res);
      this.setState({
        allDataList: allList,
      });
      const selectedRowKeys = allList.map(v=>{
        return v.id;
      }); //默认选全中
      this.handleRowSelectChange(selectedRowKeys, allList);
    })
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      startIndex: ( pagination.current - 1 ) * pagination.pageSize,  //此处峻吉分页需要是第一项的序号，如第二页传10，而不是具体的分页码1，2，3
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,

    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'refundList/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const {form,} = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });

    this.componentDidMount();
    //
    // dispatch({
    //   type: 'businessPay/fetchBusinessOrderList',
    //   payload: {
    //     business_id : id
    //   }
    // }).then(res=>{
    //   const { selectedRowKeys } = this.state;
    //   const totalPrice = this.calculateTotalPrice(selectedRowKeys);
    //   this.setState({
    //     totalPrice,
    //   });
    // })
  };

  calculateTotalPrice = (selectedRowKeys)=>{
    let totalPrice = 0;
    const {allDataList} = this.state;
    allDataList.forEach(v=>{
      if(selectedRowKeys.includes(v.id)){
        if(v.status === 0){ //异常订单
          totalPrice -= Number(v.settlement_total);
        }else{
          totalPrice += Number(v.settlement_total);
        }
      }
    });
    return totalPrice;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRow) => {
    const {businessPay: {businessOrderList}} = this.props;
    const totalPrice = this.calculateTotalPrice(selectedRowKeys);
    const selectedRefund = [];
    const selectedOrder = [];
    selectedRow.forEach(v=>{ // 记录下选中的正常与异常订单，用于分开提交
      if(v.status === 0){
        selectedRefund.push(v.id);
      }else{
        selectedOrder.push(v.id);
      }
    });
    this.setState({
      selectedRowKeys,
      totalPrice,
      selectedRefund,
      selectedOrder
    });
  };

  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form, id} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        business_id : id,
        ...fieldsValue,
      };
      if (Array.isArray(fieldsValue.time)) {
        values.startTime = fieldsValue.time[0].format('YYYY-MM-DD');
        values.endTime = fieldsValue.time[1].format('YYYY-MM-DD');
      }
      delete values.time;

      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'businessPay/fetchBusinessOrderList',
        payload: values
      }).then(allList=>{
        this.setState({
          allDataList: allList,
        });
        try{
          const selectedRowKeys = allList.map(v=>{
            return v.id;
          }); //默认选全中
          this.handleRowSelectChange(selectedRowKeys, allList);
        }catch(err){
          console.log(err);
        }
      })
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  okHandle = ()=>{
    const { selectedRowKeys, totalPrice, selectedRefund, selectedOrder } = this.state;
    const { dispatch, id } = this.props;
    if(totalPrice < 0){
      message.error('可结算金额小于0，暂不可结算');
      return false;
    }
    else if(selectedRowKeys.length === 0){
      message.error('请选择需要结算的订单');
      return false;
    }
    dispatch({
      type: 'businessPay/createBusinessPay',
      payload: {
        business_id: id ,
        order_list:selectedOrder,
        refund_order_list: selectedRefund,
      }
    }).then(res=>{
      if(res){
        message.success('已生成结算批次号');
        setTimeout(function(){
          dispatch(
            routerRedux.push({
              pathname: `/order/business-pay-detail`,
              search: `?id=${res}`
            })
          );
        },1000);
      }
    })
  }

  renderForm() {
    const {getFieldDecorator} = this.props.form;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="商品SKUID">
              {getFieldDecorator('skuId')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="订单ID">
              {getFieldDecorator('orderId')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="商品名称">
              {getFieldDecorator('name')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="电话号码">
              {getFieldDecorator('phone')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="收件人">
              {getFieldDecorator('addressee')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>
          <Col md={16} sm={24}>
            <FormItem label="下单时间">
              {getFieldDecorator('time')(
                <RangePicker style={{width: '100%'}} placeholder={['开始日期', '结束日期']}/>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                筛选
              </Button>
              <Button style={{marginLeft: 8}} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {businessPay: {businessOrderList}, loading, modalVisible, onModalVisible} = this.props;
    const {selectedRowKeys, totalPrice} = this.state;

    return (
      <Modal
        style={{ top: 20 }}
        width="1024"
        title="订单列表"
        visible={modalVisible}
        onOk={this.okHandle}
        onCancel={()=>{onModalVisible(false)}}
      >
        {this.renderForm()}
        <StandardTable
          loading={loading}
          data={businessOrderList}
          columns={columns}
          onChange={this.handleStandardTableChange}
          rowKey={'id'}
          expandedRowRender={null}
          selectedRowKeys={selectedRowKeys}
          handleRowSelectChange={this.handleRowSelectChange}
          totalPrice={totalPrice}
        />
      </Modal>
    );
  }
}
